package com.sita.bike.support;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.sita.bike.persistence.DaoMaster;
import com.sita.bike.persistence.RouteDao;
import com.sita.bike.persistence.TracksDao;
import com.sita.bike.persistence.TrendMemberDao;
import com.sita.bike.utils.LogUtils;

import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by hongyun on 2016/3/14.
 */
public class ReleaseOpenHelper extends DaoMaster.OpenHelper {


    private static String TAG = ReleaseOpenHelper.class.getSimpleName();
    private static String DB_NAME = "";

    private static final SortedMap<Integer, Migration> ALL_MIGRATIONS = new TreeMap<>();

    static {
        // each version has its own migration function
        ALL_MIGRATIONS.put(1, new V1Migration());
        ALL_MIGRATIONS.put(2, new V2Migration());
        ALL_MIGRATIONS.put(3, new V3Migration());
    }

    public ReleaseOpenHelper(Context context, String dbname, SQLiteDatabase.CursorFactory factory) {
        super(context, dbname, factory);
        DB_NAME = dbname;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        LogUtils.w(TAG, "Create database......");
        super.onCreate(db);
//        executeMigrations(db, ALL_MIGRATIONS.keySet());
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        DaoMaster.createAllTables(sqLiteDatabase, true);
        LogUtils.w(TAG, "Upgrade from" + oldVersion + "to" + newVersion);
        SortedMap<Integer, Migration> migrations = ALL_MIGRATIONS.subMap(oldVersion, newVersion);
        executeMigrations(sqLiteDatabase, migrations.keySet());

    }

    private void executeMigrations(final SQLiteDatabase paramSQLiteDatabase, final Set<Integer>
            migrationVersions) {
        for (final Integer version : migrationVersions) {
            ALL_MIGRATIONS.get(version).migrate(paramSQLiteDatabase);
        }
    }


    /**********************
     * Migration Functions
     ***************************/

    public static interface Migration {

        void migrate(SQLiteDatabase db);

    }

    public static class V1Migration implements Migration {

        @Override
        public void migrate(SQLiteDatabase db) {

            LogUtils.w(TAG, "V1Migration doing......");

            // 添加新表
            TrendMemberDao.createTable(db, true);

//
//            // 删除表
//            UserDao.dropTable(db, true);
        }
    }

    public static class V2Migration implements Migration {

        @Override
        public void migrate(SQLiteDatabase db) {

            LogUtils.w(TAG, "V2Migration doing......");

        }
    }

    public static class V3Migration implements Migration {

        @Override
        public void migrate(SQLiteDatabase db) {

            LogUtils.w(TAG, "V3Migration doing......");

            TracksDao.dropTable(db, true);
        }
    }
}
